﻿using System;
using System.IO;
using System.Reflection;
using System.Security;
using System.Windows;
using System.Windows.Forms;
using LisenceUtils.Enums;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LisenceUtils.Windows
{
    /// <summary>
    ///     Interaction logic for LicenseGenerate.xaml
    /// </summary>
    public partial class LicenseGenerate : Window
    {
        private static readonly IHardwareInfoHandle HardwareInfoHandle = LisenceUtils.HardwareInfoHandle.Create();
        private readonly Assembly _assembly = Assembly.GetExecutingAssembly();
        private readonly SecureString _certPwd = new SecureString();

        public LicenseGenerate()
        {
            InitializeComponent();
            //生成的证书密码
            _certPwd.AppendChar('d');
            _certPwd.AppendChar('e');
            _certPwd.AppendChar('m');
            _certPwd.AppendChar('o');
        }

        public LicenseEntity License { get; set; }

        public byte[] CertificatePrivateKeyData { set; get; }

        public SecureString CertificatePassword { set; get; }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            using (var mem = new MemoryStream())
            {
                var manifestResourceStream = _assembly.GetManifestResourceStream("LisenceUtils.LicenseSign.pfx");
                manifestResourceStream?.CopyTo(mem);
                CertificatePrivateKeyData = mem.ToArray();
                CertificatePassword = _certPwd;
                License = MyLicense.Default;
            }
        }

        private void CreateLicense(object sender, RoutedEventArgs e)
        {
            if (License == null) return;
            if (HardwareInfoHandle.ValidateUidFormat(TxtUid.Text.Trim()))
            {
                License.Type = LicenseTypes.Single;
                License.Uid = TxtUid.Text.Trim();
            }
            else
            {
                MessageBox.Show("验证码xxxx-xxxx-xxxx-xxxx空白或无效", "警告", MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }
            License.CreateDateTime = DateTime.Now;

            var licStr = License.GenerateLicenseBase64String(CertificatePrivateKeyData, CertificatePassword);
            LicenseCode.Text = licStr;
        }
    }
}